package main.java.Fzy.Work.task01;

import java.util.Arrays;

public class Demo3 {
    public static void main(String[] args) {

        int nums[] = new int[10];
        for(int i = 0;i<nums.length;i++){
            nums[i] = (int) (Math.random()*100);
        }
        System.out.println("排序前："+Arrays.toString(nums));
        sort(nums,0,nums.length-1);
        System.out.println("排序后："+Arrays.toString(nums));
    }

    /***
    * @author LazyCat
    * @date  2022/11/19
    * @param nums 传入数组
     * @param left 左边界
     * @param right 右边界
    * @return
     * 递归排序
    */
    public static void sort(int[] nums,int left,int right){

        if(left>=right){
            return;
        }
        int mid = (left+right)/2;
        sort(nums,left,mid);
        sort(nums,mid+1,right);
        merge(nums,left,mid,right);
    }
    /**
    * @author LazyCat
    * @date  2022/11/19
    * @param nums 出入归并数组
     * @param left 数组开始位置
     * @param mid 数组中间位置
     * @param right 数组结束位置
    * @return
     * 归并
    */
    public static void merge(int[] nums,int left,int mid,int right){
        int[] tmpArr = new int[nums.length];
        int start = mid+1;  //右边界开始索引
        int third = left;   //记录临时数组索引
        int tmp = left;     //缓存索引
        while (left<=mid && start<=right){
            if(nums[left] <= nums[start]){
                tmpArr[third++] = nums[left++];
            }else {
                tmpArr[third++] = nums[start++];
            }
        }

        while (start <= right){
            tmpArr[third++] = nums[start++];
        }
        while (left <= mid){
            tmpArr[third++] = nums[left++];
        }

        while (tmp <= right){
            nums[tmp] = tmpArr[tmp++];
        }
    }
}
